package org.oak.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * org.oak.interceptor.LoggingInterceptor
 *
 * @author ZRS
 * @version V1.0
 * @since 2025/10/30 17:07
 */
@Component
public class LoggingInterceptor implements HandlerInterceptor {

    static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        logger.info("请求开始: {}", url);
        // 记录请求开始时间
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 可以在这里修改模型数据或视图
        if (modelAndView != null) {
            modelAndView.addObject("commonAttr", "通用属性");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 计算请求处理时间
        Long startTime = (Long) request.getAttribute("startTime");
        if (startTime != null) {
            long executionTime = System.currentTimeMillis() - startTime;
            logger.info("请求结束，耗时: {}ms", executionTime);
        }

        // 处理异常信息
        if (ex != null) {
            logger.error("请求处理异常: {}", ex.getMessage());
        }
    }
}
